package com.bobi.tfca.ui.mainnavigation.message.letter

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.bobi.tfca.network.ApiResponse
import com.bobi.tfca.network.api.MessageAPI
import com.bobi.tfca.network.response.MessageResponse
import com.bobi.tfca.util.LogUtil
import com.bobi.tfca.viewmodel.PublicViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class LetterDetailFragmentVM : ViewModel() {

    val letter by lazy {
        MutableLiveData(MessageResponse())
    }

    /**
     * 根据Id获取信件
     * 主要是获取信件内容1
     */
    fun getLetterById(
        publicViewModel: PublicViewModel,
        letterId: Long,
        letterDetailFragment: LetterDetailFragment
    ) {
        publicViewModel.apply {
            request(MessageAPI::class.java).getLetterById(letterId).getResponse {
                it.collect {
                    when (it) {
                        is ApiResponse.Error -> {
                            LogUtil.e(it.errMsg)
                        }

                        ApiResponse.Loading -> LogUtil.e("Loading")
                        is ApiResponse.Success -> {
                            withContext(Dispatchers.Main) {
                                val result = it.data?.data
                                if (result != null) {
                                    letter.value = result
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}